<template>
  <div style="position:relative;width:100%;height:475px;">
    <div id="realTime-map"></div>
  </div>
</template>
<script>
import AMap from 'AMap'
import { mapState } from 'vuex'
import SHOP_PNG from './imgs/shop.png'
import HYDRANT_PNG from './imgs/hydrant.png'
import FIRE_DETACH_PNG from './imgs/fireDetachment.png'
import MEDICAL_PNG from './imgs/medical.png'
import MINI_FIRESTATION_PNG from './imgs/miniFireStation.png'
import ALARM_PNG from './imgs/alarm.png'
import { getShopLocation } from '@/api/monitor'
export default {
  // props: {
  //   dataSource: {
  //     type: Array,
  //     default: function() {
  //       return [];
  //     }
  //   }
  // },
  data() {
    return {
      mapHeight: 800,
      points: [],
      map: '',
      MarkerClustererMarker: '',
      vMarkerClustererMarkers: [],
      vMarkerClustererStatus: true
    }
  },
  // watch: {
  //   dataSource(curVal, oldVal) {
  //     this.points = curVal;
  //     // this.PointSimplifierInit();
  //   }
  // },
  computed: {
    ...mapState({
      lat: state => state.user.lat,
      lng: state => state.user.lng
    })
  },
  mounted() {
    this.mapInit()
    this.getPoints()
    this.addPolygon(this.lng, this.lat)
  },
  methods: {
    updateDatas(data) {
      this.$emit('sendData', data)
    },
    mapSetZoomCenter(lng, lat) {
      this.map.setZoomAndCenter(20, [lng, lat])
    },
    addAlarm(obj) {
      let marker = new AMap.Marker({
        position: new AMap.LngLat(parseFloat(obj.lng), parseFloat(obj.lat)),
        icon: new AMap.Icon({
          image: ALARM_PNG,
          size: new AMap.Size(48, 48), //图标大小
          imageSize: new AMap.Size(48, 48)
        }),

        zIndex: 999,
        // content:
        //   '<div style="background-color: hsla(180, 100%, 50%, 0.7); height: 24px; width: 24px; border: 1px solid hsl(180, 100%, 40%); border-radius: 12px; box-shadow: hsl(180, 100%, 50%) 0px 0px 1px;"></div>',
        offset: new AMap.Pixel(-15, -15)
      })
      var infoWindow = new AMap.InfoWindow({
        isCustom: true,
        offset: new AMap.Pixel(20, -30)
      })
      let _this = this
      marker.on('click', markerClick)
      function markerClick(e) {
        //实例化信息窗体
        var title = obj.shopName
        var content = []
        content.push(`<p ><span>设备名称 :</span> ${obj.deviceName}</p>`)
        content.push(`<p ><span>告警类型 :</span> ${obj.msgType}</p>`)
        content.push(`<p ><span> 告警信息:</span> ${obj.alarmData}</p>`)
        content.push(`<p ><span>告警时间 :</span> ${obj.alarmTime}</p>`)
        content.push(`<p ><span>商铺地址 :</span>${obj.addr}</p></div>`)

        //构建自定义信息窗体
        function createInfoWindow(title, content) {
          var info = document.createElement('div')
          info.className = 'custom-info input-card content-window-card'

          //可以通过下面的方式修改自定义窗体的宽高
          //info.style.width = "400px";
          // 定义顶部标题
          var top = document.createElement('div')
          var titleD = document.createElement('div')
          var closeX = document.createElement('img')
          top.className = 'info-top'
          titleD.innerHTML = title
          closeX.src = 'https://webapi.amap.com/images/close2.gif'
          closeX.onclick = closeInfoWindow

          top.appendChild(titleD)
          top.appendChild(closeX)
          info.appendChild(top)

          // 定义中部内容
          var middle = document.createElement('div')
          middle.className = 'info-middle'
          middle.style.backgroundColor = 'white'
          middle.innerHTML = content
          info.appendChild(middle)

          // 定义底部内容
          var bottom = document.createElement('div')
          bottom.className = 'info-bottom'
          bottom.style.position = 'relative'
          bottom.style.top = '0px'
          bottom.style.margin = '0 auto'
          var sharp = document.createElement('img')
          sharp.src = 'https://webapi.amap.com/images/sharp.png'
          bottom.appendChild(sharp)
          info.appendChild(bottom)
          return info
        }

        //关闭信息窗体
        function closeInfoWindow() {
          this.map.clearInfoWindow()
        }

        infoWindow.setContent(createInfoWindow(title, content.join('')))
        infoWindow.open(_this.map, e.target.getPosition())
      }
      this.map.add(marker)
      this.map.setZoomAndCenter(20, [obj.lng, obj.lat])
    },
    mapInit() {
      // let lat = 34;
      // let lng = 105;
      let zoom = 5
      // if (this.lat && this.lng) {
      //   lat = this.lat;
      //   lng = this.lng;
      //   zoom = 15;
      // }
      this.map = new AMap.Map('realTime-map', {
        resizeEnable: true,
        expandZoomRange: true,
        zooms: [3, 20],
        // center: [lng, lat],
        zoom: zoom
        // mapStyle: "amap://styles/darkblue"
      })
    },
    markerClustererInit() {
      var points = this.points
      if (points.length > 0) {
        const _this = this
        for (let i = 0; i < points.length; i++) {
          let iconSrc = SHOP_PNG
          if (points[i].shopPlace == 11) {
            iconSrc = HYDRANT_PNG
          } else if (points[i].shopPlace == 12) {
            iconSrc = MINI_FIRESTATION_PNG
          } else if (points[i].shopPlace == 13) {
            iconSrc = MEDICAL_PNG
          } else if (points[i].shopPlace == 14) {
            iconSrc = FIRE_DETACH_PNG
          }
          let marker = new AMap.Marker({
            position: new AMap.LngLat(points[i].lng, points[i].lat),
            icon: new AMap.Icon({
              image: iconSrc,
              size: new AMap.Size(48, 48), //图标大小
              imageSize: new AMap.Size(48, 48)
            }),
            // content:
            //   '<div style="background-color: hsla(180, 100%, 50%, 0.7); height: 24px; width: 24px; border: 1px solid hsl(180, 100%, 40%); border-radius: 12px; box-shadow: hsl(180, 100%, 50%) 0px 0px 1px;"></div>',
            offset: new AMap.Pixel(-15, -15),
            extData: i
          })
          var infoWindow = new AMap.InfoWindow({
            isCustom: true,
            offset: new AMap.Pixel(20, -30)
          })

          marker.content = i
          marker.on('click', markerClick)
          function markerClick(e) {
            //构建信息窗体中显示的内容
            var index = e.target.content
            var shop = points[index]

            //实例化信息窗体
            var title = shop.shopName
            var content = []
            content.push(`<p ><span>所属部门 :</span> ${shop.depName}</p>`)
            content.push(`<p ><span>负责人 :</span> ${shop.managerName}</p>`)
            content.push(
              `<p ><span>联系电话 :</span> ${shop.managerMobile}</p>`
            )
            content.push(`<p ><span>设备数 :</span> ${shop.devCount}</p>`)
            content.push(`<p ><span>IMEI :</span> ${shop.imei}</p>`)
            content.push(`<p ><span>商铺地址 :</span>${shop.addr}</p></div>`)
            // var infoWindow = new AMap.InfoWindow({
            //   isCustom: true, //使用自定义窗体
            //   content: createInfoWindow(title, content.join("<br/>")),
            //   offset: new AMap.Pixel(16, -45)
            // });

            //构建自定义信息窗体
            function createInfoWindow(title, content) {
              var info = document.createElement('div')
              info.className = 'custom-info input-card content-window-card'

              //可以通过下面的方式修改自定义窗体的宽高
              //info.style.width = "400px";
              // 定义顶部标题
              var top = document.createElement('div')
              var titleD = document.createElement('div')
              var closeX = document.createElement('img')
              top.className = 'info-top'
              titleD.innerHTML = title
              closeX.src = 'https://webapi.amap.com/images/close2.gif'
              closeX.onclick = closeInfoWindow

              top.appendChild(titleD)
              top.appendChild(closeX)
              info.appendChild(top)

              // 定义中部内容
              var middle = document.createElement('div')
              middle.className = 'info-middle'
              middle.style.backgroundColor = 'white'
              middle.innerHTML = content
              info.appendChild(middle)

              // 定义底部内容
              var bottom = document.createElement('div')
              bottom.className = 'info-bottom'
              bottom.style.position = 'relative'
              bottom.style.top = '0px'
              bottom.style.margin = '0 auto'
              var sharp = document.createElement('img')
              sharp.src = 'https://webapi.amap.com/images/sharp.png'
              bottom.appendChild(sharp)
              info.appendChild(bottom)
              return info
            }

            //关闭信息窗体
            function closeInfoWindow() {
              _this.map.clearInfoWindow()
            }

            infoWindow.setContent(createInfoWindow(title, content.join('')))
            infoWindow.open(_this.map, e.target.getPosition())
          }
          _this.vMarkerClustererMarkers.push(marker)
        }
        // AMap.plugin(["AMap.ToolBar", "AMap.MouseTool", "AMap.MarkerClusterer"]);
        AMap.plugin(
          ['AMap.ToolBar', 'AMap.Scale', 'AMap.OverView', 'AMap.MapType'],
          function() {
            // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
            _this.map.addControl(new AMap.ToolBar())

            // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
            _this.map.addControl(new AMap.Scale())

            // 在图面添加鹰眼控件，在地图右下角显示地图的缩略图
            _this.map.addControl(new AMap.OverView({ isOpen: true }))

            // 在图面添加类别切换控件，实现默认图层与卫星图、实施交通图层之间切换的控制
            _this.map.addControl(new AMap.MapType())
          }
        )
        _this.map.plugin(['AMap.MarkerClusterer'], function() {
          _this.MarkerClustererMarker = new AMap.MarkerClusterer(
            _this.map, // 地图实例
            _this.vMarkerClustererMarkers, // 海量点组成的数组
            { gridSize: 80, minClusterSize: 10 }
          )
        })
        // AMap.plugin(["AMap.MarkerClusterer"]);
        // _this.map.addControl(
        //   (_this.MarkerClustererMarker = new AMap.MarkerClusterer(
        //     _this.map,
        //     _this.vMarkerClustererMarkers,
        //     { gridSize: 80 }
        //   ))
        // );
        // _this.map.setFitView();
      }
    },
    // PointSimplifierInit() {
    //   let points = this.points;
    //   let lat = 34;
    //   let lng = 105;
    //   let zoom = 5;
    //   if (this.lat && this.lng) {
    //     lat = this.lat;
    //     lng = this.lng;
    //     zoom = 18;
    //   }
    //   //创建地图
    //   var map = new AMap.Map("realTime-map", {
    //     expandZoomRange: true,
    //     zooms: [3, 20],
    //     center: [lng, lat],
    //     zoom: zoom,
    //     mapStyle: "amap://styles/macaron"
    //     //      pitch:20, // 地图俯仰角度，有效范围 0 度- 83 度
    //     // viewMode:'3D' // 地图模式
    //   });
    //   this.map = map;

    //   //just some colors
    //   var colors = [
    //     "#0cc2f2",
    //     "#4fd2b1",
    //     "#90e36f",
    //     "#ffe700",
    //     "#ff9e00",
    //     "#ff6700",
    //     "#ff1800"
    //   ];

    //   AMapUI.load(["ui/misc/PointSimplifier", "lib/$"], function(
    //     PointSimplifier,
    //     $
    //   ) {
    //     if (!PointSimplifier.supportCanvas) {
    //       alert("当前环境不支持 Canvas！");
    //       return;
    //     }

    //     var pointSimplifierIns = new PointSimplifier({
    //       zIndex: 115,
    //       autoSetFitView: false,
    //       map: map, //所属的地图实例

    //       getPosition: function(item) {
    //         if (!item) {
    //           return null;
    //         }

    //         // var parts = item.split(",");

    //         return [parseFloat(item.position[0]), parseFloat(item.position[1])];
    //       },
    //       getHoverTitle: function(dataItem, idx) {
    //         return "序号: " + idx;
    //       },
    //       //使用GroupStyleRender
    //       renderConstructor: PointSimplifier.Render.Canvas.GroupStyleRender,
    //       renderOptions: {
    //         eventSupport: false, //禁止事件,对性能更友好
    //         //点的样式
    //         pointStyle: {
    //           fillStyle: null,
    //           width: 5,
    //           height: 5
    //         },
    //         topNAreaStyle: null,
    //         getGroupId: function(item, idx) {
    //           //随机返回一个组ID
    //           return Math.ceil(colors.length * Math.random());
    //         },
    //         groupStyleOptions: function(gid) {
    //           //随机设置大小
    //           var radius = 2 + 5 * Math.random();

    //           return {
    //             pointStyle:
    //               radius > 0
    //                 ? {
    //                     content: function(ctx, x, y, width, height) {
    //                       var p = {
    //                         x: x + width / 2,
    //                         y: y + height / 2,
    //                         radius: radius
    //                       };

    //                       ctx.beginPath();
    //                       var gradient = ctx.createRadialGradient(
    //                         p.x,
    //                         p.y,
    //                         0,
    //                         p.x,
    //                         p.y,
    //                         p.radius
    //                       );
    //                       gradient.addColorStop(0, "rgba(0, 185, 150,0.8)");
    //                       gradient.addColorStop(1, "rgba(0, 184, 148,0.1)");
    //                       ctx.fillStyle = gradient;
    //                       ctx.arc(p.x, p.y, p.radius, Math.PI * 2, false);
    //                       ctx.fill();
    //                     },

    //                     //fillStyle: colors[gid % colors.length],
    //                     width: radius * 2,
    //                     height: radius * 2
    //                   }
    //                 : null,
    //             pointHardcoreStyle: {
    //               width: radius * 2 + 3,
    //               height: radius * 2 + 3
    //             }
    //           };
    //         }
    //       }
    //     });

    //     //重复render
    //     setInterval(function() {
    //       pointSimplifierIns.render();
    //     }, 500);
    //     //仅作示意
    //     function createPoints(pointsArr) {
    //       var data = [];
    //       for (var i = 0, len = pointsArr; i < len; i++) {
    //         data.push({
    //           position: [points[i].lng, points[i].lat]
    //         });
    //       }
    //       return data;
    //     }

    //     //随机创建一批点，仅作示意
    //     var data = createPoints(points.length);

    //     //设置数据源，data需要是一个数组
    //     pointSimplifierIns.setData(data);
    //   });
    // },
    async getPoints() {
      let res = await getShopLocation({})
      if (res.code == 0) {
        console.log(res)
        this.points = res.data
        this.markerClustererInit()
      }
    },
    addPolygon(lng, lat) {
      // this.map.clearMap();
      if (lat && lng) {
        let bound = []
        let lats = lat.split(',')
        let lngs = lng.split(',')
        lats.forEach((item, index) => {
          bound.push([item, lngs[index]])
        })
        let _this = this
        var polygon = new AMap.Polygon({
          map: _this.map,
          strokeWeight: 1,
          path: bound,
          fillOpacity: 0.7,
          fillColor: '#CCF3FF',
          strokeColor: '#CC66CC'
        })
        this.map.setFitView()
      }
    }
  }
}
</script>
<style>
#realTime-map {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  z-index: 2020;
}
.map-operator {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 200px;
  height: 85px;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: space-between;
}
.map-operator > div {
  position: relative;
  width: 52px;
  height: 52px;
  background-repeat: no-repeat;
  background-position: center center;
  background-size: 50px;
  cursor: pointer;
}

.map-operator > div > div {
  position: absolute;
  width: 52px;
  height: 22px;
  line-height: 22px;
  left: 0;
  bottom: -22px;
  font-size: 14px;
}
.marker {
  position: absolute;
  top: -20px;
  right: -118px;
  color: #fff;
  padding: 4px 10px;
  box-shadow: 1px 1px 1px rgba(10, 10, 10, 0.2);
  white-space: nowrap;
  font-size: 12px;
  font-family: '';
  background-color: #25a5f7;
  border-radius: 3px;
}
.content-window-card {
  position: relative;
  box-shadow: none;
  bottom: 0;
  left: 0;
  width: auto;
  padding: 0;
}

.content-window-card p {
  line-height: 20px;
}
.content-window-card p span {
  float: left;
  width: 58px;
  color: #a1a1a1;
}
.custom-info {
  border: solid 1px silver;
}

div.info-top {
  position: relative;
  background: none repeat scroll 0 0 #09baf0;
  border-bottom: 1px solid #ccc;
  border-radius: 5px 5px 0 0;
}

div.info-top div {
  width: 100%;
  text-align: center;
  display: inline-block;
  color: #fff;
  font-size: 14px;
  font-weight: bold;
  line-height: 31px;
  padding: 0 10px;
}

div.info-top img {
  position: absolute;
  top: 10px;
  right: 10px;
  transition-duration: 0.25s;
}

div.info-top img:hover {
  box-shadow: 0px 0px 5px #000;
}

div.info-middle {
  font-size: 12px;
  padding: 10px 10px;
  line-height: 20px;
}

div.info-bottom {
  height: 0px;
  width: 100%;
  clear: both;
  text-align: center;
}
</style>
